package com.gungnir.trial.impl.supervision;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.gungnir.trial.KeduService;
import com.gungnir.trial.entity.kedu.*;
import com.gungnir.trial.util.CommonUtils;
import com.tyrfing.common.TyrfingErrorCode;
import com.tyrfing.exceptions.TyrfingServiceException;
import com.tyrfing.model.Pagination;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author bingo
 * @date 2024-05-23
 * @title kedu对接接口
 */
@Service
@Component
public class KeduServiceImpl implements KeduService {
    @Autowired
    private MongoTemplate mongoTemplate;
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Value("${kedu.host:#{null}}")
    private String host;

    @Value("${kedu.apiKey:#{null}}")
    private String apiKey;

    @Value("${kedu.tenantCode:#{null}}")
    private String tenantCode;

    private Map<String, Object> findMapByKedu(String method, String path, Map<String, Object> items) throws TyrfingServiceException {
        if (items == null) {
            items = new HashMap<>();
        }
        String url_partial = String.format("%s?apikey=%s", path, apiKey);
        String target_url = String.format("%s%s", host, url_partial);
        //推送
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        String content = CommonUtils.objectToJson(items);
        log.info("body: {}", content);
        RequestBody body = RequestBody.create(mediaType, content == null ? "" : content);
        Request request;
        if ("GET".equals(method)) {
            request = new Request.Builder()
                    .url(target_url)
                    .get()
                    .addHeader("Content-Type", "application/json")
                    .build();
        } else {
            request = new Request.Builder()
                    .url(target_url)
                    .method(method, body)
                    .addHeader("Content-Type", "application/json")
                    .build();
        }
        try (Response response = client.newCall(request).execute()) {
            log.info("response: {}", response);
            if (response.code() == 200) {
                String bodyStr = response.body() == null ? "" : response.body().string();
                log.info("url[{}] response: {}", response.request().url().query(), bodyStr);
                return CommonUtils.jsonToHashMap(bodyStr);
            } else {
                log.error("request error, path: {}, code: {}, body: {}",
                        request.url().query(), response.code(), response.body() == null ? "" : response.body().string());
            }
        } catch (IOException e) {
            e.fillInStackTrace();
            log.error("请求失败", e);
        }
        throw new TyrfingServiceException(TyrfingErrorCode.DATA_NOT_FOUND, "获取第三方接口失败，请联系管理员.");
    }

    @Override
    public Pagination<KeduCourseVO> pageKeduCourse(Integer pageSize, Integer pageNum, Long beginTime, Long endTime, String clroCode, String userCode, String teclCode, String tenantCode) throws Exception {
        if (pageSize == null) {
            throw new TyrfingServiceException(TyrfingErrorCode.LACK_OF_PARAMETER, "缺少每页数量.");
        }
        if (pageNum == null) {
            throw new TyrfingServiceException(TyrfingErrorCode.LACK_OF_PARAMETER, "缺少当前页号.");
        }
        if (beginTime == null) {
            throw new TyrfingServiceException(TyrfingErrorCode.LACK_OF_PARAMETER, "缺少课程开始时间.");
        }
        if (endTime == null) {
            throw new TyrfingServiceException(TyrfingErrorCode.LACK_OF_PARAMETER, "缺少课程结束时间.");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String path = "/kiop-gateway-core/v1/api/courseList";
        Map<String, Object> items = new HashMap<>();
        items.put("pageIndex", pageNum);
        items.put("pageSize", pageSize);
        items.put("courBeginTime", sdf.format(new Date(beginTime)));
        items.put("courEndTime", sdf.format(new Date(endTime)));
        if (StringUtils.isNotBlank(clroCode)) {
            items.put("clroCode", clroCode);
        }
        if (StringUtils.isNotBlank(userCode)) {
            items.put("userCode", userCode);
        }
        if (StringUtils.isNotBlank(teclCode)) {
            items.put("teclCode", teclCode);
        }
        if (StringUtils.isNotBlank(tenantCode)) {
            items.put("tenantCode", tenantCode);
        } else {
            items.put("tenantCode", this.tenantCode);
        }
        //获取第三方接口body
        Map<String, Object> msgMap = findMapByKedu("POST", path, items);
        //获取封装需要的内容
        Map<String, Object> dataMap = CommonUtils.jsonToHashMap(CommonUtils.objectToJson(msgMap.get("data")));
        List<HashMap<String, Object>> list = dataMap.containsKey("list") ? CommonUtils.jsonToHashMapList(CommonUtils.objectToJson(dataMap.get("list"))) : new ArrayList<>();
        Pagination<KeduCourseVO> pagination = new Pagination<>(pageSize, pageNum);
        if (list != null && !list.isEmpty()) {
            pagination.setData(list.stream()
                    .map(course -> {
                        KeduCourseVO courseVO = new KeduCourseVO();
                        try {
                            if (course != null) {
                                for (Map.Entry<String, Object> entry :
                                        course.entrySet()) {
                                    if (entry.getValue() != null) {
                                        switch (entry.getKey()) {
                                            case "acteName":
                                                //未知名称
                                                courseVO.setActeName(String.valueOf(entry.getValue()));
                                                break;
                                            case "acyeBeginYear":
                                                //未知开始年份
                                                courseVO.setAcyeBeginYear(Integer.valueOf(String.valueOf(entry.getValue())));
                                                break;
                                            case "acyeEndYear":
                                                //未知结束年份
                                                courseVO.setAcyeEndYear(Integer.valueOf(String.valueOf(entry.getValue())));
                                                break;
                                            case "clroCode":
                                                //教室编码
                                                courseVO.setClroCode(String.valueOf(entry.getValue()));
                                                break;
                                            case "clroId":
                                                //教室Id
                                                courseVO.setClroId(Integer.valueOf(String.valueOf(entry.getValue())));
                                                break;
                                            case "clroName":
                                                //教室名称
                                                courseVO.setClroName(String.valueOf(entry.getValue()));
                                                break;
                                            case "courBeginTime":
                                                //课程开始时间
                                                courseVO.setCourBeginTime(sdf.parse(String.valueOf(entry.getValue())).getTime());
                                                break;
                                            case "courEndTime":
                                                //课程结束时间
                                                courseVO.setCourEndTime(sdf.parse(String.valueOf(entry.getValue())).getTime());
                                                break;
                                            case "letiNumber":
                                                //课程节次
                                                courseVO.setLetiNumber(Integer.valueOf(String.valueOf(entry.getValue())));
                                                break;
                                            case "liveEnable":
                                                //默认直播状态:1,启用;0,禁用
                                                courseVO.setLiveEnable(Integer.valueOf(String.valueOf(entry.getValue())));
                                                break;
                                            case "orgaNames":
                                                //组织名称
                                                courseVO.setOrgaNames(CommonUtils.objToList(entry.getValue(), String.class));
                                                break;
                                            case "subjCode":
                                                //科目编号
                                                courseVO.setSubjCode(String.valueOf(entry.getValue()));
                                                break;
                                            case "subjName":
                                                //科目名称
                                                courseVO.setSubjName(String.valueOf(entry.getValue()));
                                                break;
                                            case "teacCodes":
                                                //老师编号
                                                courseVO.setTeacCodes(CommonUtils.objToList(entry.getValue(), String.class));
                                                break;
                                            case "teacNames":
                                                //老师名称
                                                courseVO.setTeacNames(CommonUtils.objToList(entry.getValue(), String.class));
                                                break;
                                            case "teclCode":
                                                //教学班编号
                                                courseVO.setTeclCode(String.valueOf(entry.getValue()));
                                                break;
                                            case "teclName":
                                                //教学班名称
                                                courseVO.setTeclName(String.valueOf(entry.getValue()));
                                                break;
                                            case "vodEnable":
                                                //默认点播状态:1,启用;0,禁用
                                                courseVO.setVodEnable(Integer.valueOf(String.valueOf(entry.getValue())));
                                                break;
                                            case "vodStatus":
                                                //课程结束后点播文件剪辑状态：1-生成中 2-已完成 3-无录像 4-生成失败
                                                courseVO.setVodStatus(Integer.valueOf(String.valueOf(entry.getValue())));
                                                break;
                                        }
                                    }
                                }
                            }
                        } catch (ParseException e) {
                            log.error("error {}", e.getMessage());
                        }
                        return courseVO;
                    })
                    .collect(Collectors.toList()));
        }
        if (dataMap.containsKey("totalCount")) {
            pagination.setTotal(Integer.parseInt(String.valueOf(dataMap.get("totalCount"))));
        } else {
            pagination.setTotal(0);
        }
        return pagination;
    }

    @Override
    public KeduLiveUrlVO findKeduLiveUrl(String clroCode, String playType, List<Integer> deviViewNum, String tenantCode) throws TyrfingServiceException {
        if (StringUtils.isBlank(clroCode)) {
            throw new TyrfingServiceException(TyrfingErrorCode.LACK_OF_PARAMETER, "缺少教室编号.");
        }
        if (StringUtils.isBlank(playType)) {
            throw new TyrfingServiceException(TyrfingErrorCode.LACK_OF_PARAMETER, "缺少播放类型.");
        }
        String playTypes = "hls,flv,webrtc,rtmp";
        if (!playTypes.contains(playType)) {
            throw new TyrfingServiceException(TyrfingErrorCode.ILLEGAL_STATE, "未知的播放类型.");
        }
        String path = "/kiop-gateway-core/v1/api/getLiveUrl";
        Map<String, Object> items = new HashMap<>();
        items.put("clroCode", clroCode);
        items.put("playType", playType);
        if (deviViewNum != null && !deviViewNum.isEmpty()) {
            items.put("deviViewNum", deviViewNum);
        }
        if (StringUtils.isNotBlank(tenantCode)) {
            items.put("tenantCode", tenantCode);
        } else {
            items.put("tenantCode", this.tenantCode);
        }
        //获取第三方接口body
        Map<String, Object> msgMap = findMapByKedu("POST", path, items);
        //获取封装需要的内容
        Map<String, Object> dataMap = CommonUtils.jsonToHashMap(CommonUtils.objectToJson(msgMap.get("data")));
        KeduLiveUrlVO liveUrl = null;
        if (dataMap != null) {
            liveUrl = new KeduLiveUrlVO();
            for (Map.Entry<String, Object> entryItem :
                    dataMap.entrySet()) {
                if (entryItem.getValue() != null) {
                    switch (entryItem.getKey()) {
                        case "clroCode":
                            //教室编号
                            liveUrl.setClroCode(String.valueOf(entryItem.getValue()));
                            break;
                        case "courId":
                            //课程id
                            liveUrl.setCourId(String.valueOf(entryItem.getValue()));
                            break;
                        case "deviceViewList":
                            try {
                                //教室绑定的设备视角
                                List<HashMap<String, Object>> list = CommonUtils.jsonToHashMapList(CommonUtils.objectToJson(entryItem.getValue()));
                                if (list != null && !list.isEmpty()) {
                                    liveUrl.setDeviceViewList(list.stream()
                                            .map(item -> {
                                                KeduDeviceLiveUrlVO deviceLiveUrl = new KeduDeviceLiveUrlVO();
                                                if (item != null) {
                                                    for (Map.Entry<String, Object> entry :
                                                            item.entrySet()) {
                                                        if (entry.getValue() != null) {
                                                            switch (entry.getKey()) {
                                                                case "deviViewNum":
                                                                    //视角编号：1: '教师1',2: '教师2',3: '学生1',4: '学生2',5: 'PPT',6: '电子白板',7: '合成通道'
                                                                    deviceLiveUrl.setDeviViewNum(Integer.valueOf(String.valueOf(entry.getValue())));
                                                                    break;
                                                                case "deviceStatus":
                                                                    //设备状态
                                                                    deviceLiveUrl.setDeviceStatus(Integer.valueOf(String.valueOf(entry.getValue())));
                                                                    break;
                                                                case "playUrl":
                                                                    //主流通道直播播放url
                                                                    deviceLiveUrl.setPlayUrl(String.valueOf(entry.getValue()));
                                                                    break;
                                                                case "gbId":
                                                                    //主流通道设备视角国标ID
                                                                    deviceLiveUrl.setGbId(String.valueOf(entry.getValue()));
                                                                    break;
                                                                case "secondPlayUrl":
                                                                    //辅流通道直播播放url
                                                                    deviceLiveUrl.setSecondPlayUrl(String.valueOf(entry.getValue()));
                                                                    break;
                                                                case "secondGbId":
                                                                    //辅流通道设备视角国标ID
                                                                    deviceLiveUrl.setSecondGbId(String.valueOf(entry.getValue()));
                                                                    break;
                                                            }
                                                        }
                                                    }
                                                }
                                                return deviceLiveUrl;
                                            })
                                            .collect(Collectors.toList()));
                                }
                            } catch (IOException e) {
                                liveUrl.setDeviceViewList(new ArrayList<>());
                            }
                            break;
                        case "liveEnable":
                            //默认直播状态:1,启用;0,禁用
                            liveUrl.setLiveEnable(Integer.valueOf(String.valueOf(entryItem.getValue())));
                            break;
                    }
                }
            }
        }
        return liveUrl;
    }

    @Override
    public KeduVideoUrlVO findKeduVideoUrl(String clroCode, Long startTime, Long endTime, String tenantCode) throws TyrfingServiceException {
        if (StringUtils.isBlank(clroCode)) {
            throw new TyrfingServiceException(TyrfingErrorCode.LACK_OF_PARAMETER, "缺少教室编号.");
        }
        if (startTime == null) {
            throw new TyrfingServiceException(TyrfingErrorCode.LACK_OF_PARAMETER, "缺少开始时间.");
        }
        if (endTime == null) {
            throw new TyrfingServiceException(TyrfingErrorCode.LACK_OF_PARAMETER, "缺少结束时间.");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String path = "/kiop-gateway-core/v1/api/getVideoUrl";
        Map<String, Object> items = new HashMap<>();
        items.put("startTime", sdf.format(new Date(startTime)));
        items.put("endTime", sdf.format(new Date(endTime)));
        if (StringUtils.isNotBlank(clroCode)) {
            items.put("clroCode", clroCode);
        }
        if (StringUtils.isNotBlank(tenantCode)) {
            items.put("tenantCode", tenantCode);
        } else {
            items.put("tenantCode", this.tenantCode);
        }
        //获取第三方接口body
        Map<String, Object> msgMap = findMapByKedu("POST", path, items);
        //获取封装需要的内容
        Map<String, Object> dataMap = CommonUtils.jsonToHashMap(CommonUtils.objectToJson(msgMap.get("data")));
        KeduVideoUrlVO videoUrl = null;
        if (dataMap != null) {
            videoUrl = new KeduVideoUrlVO();
            for (Map.Entry<String, Object> entryItem :
                    dataMap.entrySet()) {
                if (entryItem.getValue() != null) {
                    switch (entryItem.getKey()) {
                        case "clroCode":
                            //教室编号
                            videoUrl.setClroCode(String.valueOf(entryItem.getValue()));
                            break;
                        case "records":
                            //课程集合
                            try {
                                List<HashMap<String, Object>> courseList = CommonUtils.jsonToHashMapList(CommonUtils.objectToJson(entryItem.getValue()));
                                if (courseList != null && !courseList.isEmpty()) {
                                    videoUrl.setCourseVideoUrlList(courseList.stream()
                                            .map(courseItem -> {
                                                KeduCourseVideoUrlVO courseVideoUrl = new KeduCourseVideoUrlVO();
                                                try {
                                                    if (courseItem != null) {
                                                        for (Map.Entry<String, Object> courseEntry :
                                                                courseItem.entrySet()) {
                                                            if (courseEntry.getValue() != null) {
                                                                switch (courseEntry.getKey()) {
                                                                    case "courBeginTime":
                                                                        //课程开始时间
                                                                        courseVideoUrl.setCourBeginTime(sdf.parse(String.valueOf(courseEntry.getValue())).getTime());
                                                                        break;
                                                                    case "courEndTime":
                                                                        //课程结束时间
                                                                        courseVideoUrl.setCourEndTime(sdf.parse(String.valueOf(courseEntry.getValue())).getTime());
                                                                        break;
                                                                    case "courId":
                                                                        //课程Id
                                                                        courseVideoUrl.setCourId(Integer.valueOf(String.valueOf(courseEntry.getValue())));
                                                                        break;
                                                                    case "deviceViewList":
                                                                        //教室绑定的设备视角
                                                                        List<HashMap<String, Object>> list = CommonUtils.jsonToHashMapList(CommonUtils.objectToJson(courseEntry.getValue()));
                                                                        if (list != null && !list.isEmpty()) {
                                                                            courseVideoUrl.setDeviceViewList(list.stream()
                                                                                    .map(item -> {
                                                                                        KeduDeviceVideoUrlVO deviceVideoUrl = new KeduDeviceVideoUrlVO();
                                                                                        if (item != null) {
                                                                                            for (Map.Entry<String, Object> entry :
                                                                                                    item.entrySet()) {
                                                                                                if (entry.getValue() != null) {
                                                                                                    switch (entry.getKey()) {
                                                                                                        case "deviViewNum":
                                                                                                            //视角编号：1: '教师1',2: '教师2',3: '学生1',4: '学生2',5: 'PPT',6: '电子白板',7: '合成通道'
                                                                                                            deviceVideoUrl.setDeviViewNum(Integer.valueOf(String.valueOf(entry.getValue())));
                                                                                                            break;
                                                                                                        case "deviceStatus":
                                                                                                            //设备状态
                                                                                                            deviceVideoUrl.setDeviceStatus(Integer.valueOf(String.valueOf(entry.getValue())));
                                                                                                            break;
                                                                                                        case "playUrl":
                                                                                                            //主流通道直播播放url
                                                                                                            deviceVideoUrl.setPlayUrl(String.valueOf(entry.getValue()));
                                                                                                            break;
                                                                                                        case "gbId":
                                                                                                            //主流通道设备视角国标ID
                                                                                                            deviceVideoUrl.setGbId(String.valueOf(entry.getValue()));
                                                                                                            break;
                                                                                                        case "secondPlayUrl":
                                                                                                            //辅流通道直播播放url
                                                                                                            deviceVideoUrl.setSecondPlayUrl(String.valueOf(entry.getValue()));
                                                                                                            break;
                                                                                                        case "secondGbId":
                                                                                                            //辅流通道设备视角国标ID
                                                                                                            deviceVideoUrl.setSecondGbId(String.valueOf(entry.getValue()));
                                                                                                            break;
                                                                                                    }
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                        return deviceVideoUrl;
                                                                                    })
                                                                                    .collect(Collectors.toList()));
                                                                        }
                                                                        break;
                                                                    case "subjCode":
                                                                        //科目编号
                                                                        courseVideoUrl.setSubjCode(String.valueOf(courseEntry.getValue()));
                                                                        break;
                                                                    case "subjName":
                                                                        //科目名称
                                                                        courseVideoUrl.setSubjName(String.valueOf(courseEntry.getValue()));
                                                                        break;
                                                                    case "teacCodes":
                                                                        //老师编号
                                                                        courseVideoUrl.setTeacCodes(CommonUtils.objToList(courseEntry.getValue(), String.class));
                                                                        break;
                                                                    case "teacNames":
                                                                        //老师名称
                                                                        courseVideoUrl.setTeacNames(CommonUtils.objToList(courseEntry.getValue(), String.class));
                                                                        break;
                                                                }
                                                            }
                                                        }
                                                    }
                                                } catch (Exception e) {
                                                    log.error("error {}", e.getMessage());
                                                }
                                                return courseVideoUrl;
                                            })
                                            .collect(Collectors.toList()));
                                }
                            } catch (IOException e) {
                                videoUrl.setCourseVideoUrlList(new ArrayList<>());
                            }
                            break;
                    }
                }
            }
        }
        return videoUrl;
    }

    @Override
    public ClassroomVO findKeduDeviceViewInfo(String clroCode, Long startTime, Long endTime, String tenantCode) throws TyrfingServiceException {
        if (tenantCode == null) {
            tenantCode = this.tenantCode;
        }
        if (StringUtils.isBlank(clroCode) || startTime == null || endTime == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> items = new HashMap<>();
        items.put("clroCode", clroCode);
        items.put("startTime", sdf.format(new Date(startTime)));
        items.put("endTime", sdf.format(new Date(endTime)));
        items.put("tenantCode", tenantCode);
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        Gson gson = new Gson();
        RequestBody body = RequestBody.create(mediaType, gson.toJson(items));
        Request request = new Request.Builder()
                .url(host + "/kiop-gateway-core/v1/api/getVideoRecord?apikey=" + apiKey)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful() && response.body() != null) {
                String res = response.body().string();
                JsonParser parser = new JsonParser();
                JsonObject jsonObject = parser.parse(res).getAsJsonObject();
                JsonElement data = jsonObject.get("data");
                if (data == null || data.isJsonNull()) {
                    return null;
                }
                return gson.fromJson(data, ClassroomVO.class);
            }
        } catch (IOException e) {
            e.fillInStackTrace();
        }
        return null;
    }

    @Override
    public List<KeduVideoUrlWithExtInfoVO> listKeduVideoUrlWithExtInfo(String teacCode, Long startTime, Long endTime, String tenantCode) throws Exception {
        if (StringUtils.isBlank(teacCode)) {
            throw new TyrfingServiceException(TyrfingErrorCode.LACK_OF_PARAMETER, "缺少教师编号.");
        }
        if (startTime == null) {
            throw new TyrfingServiceException(TyrfingErrorCode.LACK_OF_PARAMETER, "缺少开始时间.");
        }
        if (endTime == null) {
            throw new TyrfingServiceException(TyrfingErrorCode.LACK_OF_PARAMETER, "缺少结束时间.");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String path = "/kiop-gateway-core/v1/api/getVideoUrlWithExtInfo";
        Map<String, Object> items = new HashMap<>();
        items.put("startTime", sdf.format(new Date(startTime)));
        items.put("endTime", sdf.format(new Date(endTime)));
        if (StringUtils.isNotBlank(teacCode)) {
            items.put("teacCode", teacCode);
        }
        if (StringUtils.isNotBlank(tenantCode)) {
            items.put("tenantCode", tenantCode);
        } else {
            items.put("tenantCode", this.tenantCode);
        }
        //获取第三方接口body
        Map<String, Object> msgMap = findMapByKedu("POST", path, items);
        //获取封装需要的内容
        List<HashMap<String, Object>> dataMapList = CommonUtils.jsonToHashMapList(CommonUtils.objectToJson(msgMap.get("data")));
        List<KeduVideoUrlWithExtInfoVO> videoUrlList = new ArrayList<>();
        if (dataMapList != null && !dataMapList.isEmpty()) {
            videoUrlList = dataMapList.stream()
                    .map(dataItem -> {
                        KeduVideoUrlWithExtInfoVO videoUrlWithExtInfo = new KeduVideoUrlWithExtInfoVO();
                        for (Map.Entry<String, Object> entryItem :
                                dataItem.entrySet()) {
                            if (entryItem.getValue() != null) {
                                switch (entryItem.getKey()) {
                                    case "clroCode":
                                        //教室编号
                                        videoUrlWithExtInfo.setClroCode(String.valueOf(entryItem.getValue()));
                                        break;
                                    case "records":
                                        //课程集合
                                        List<HashMap<String, Object>> courseList = new ArrayList<>();
                                        try {
                                            courseList = CommonUtils.jsonToHashMapList(CommonUtils.objectToJson(entryItem.getValue()));
                                        } catch (IOException e) {
                                            log.error("error {}", e.getMessage());
                                        }
                                        if (courseList != null && !courseList.isEmpty()) {
                                            videoUrlWithExtInfo.setCourseVideoUrlWithExtInfoList(courseList.stream()
                                                    .map(courseItem -> {
                                                        KeduCourseVideoUrlWithExtInfoVO courseVideoUrl = new KeduCourseVideoUrlWithExtInfoVO();
                                                        try {
                                                            if (courseItem != null) {
                                                                for (Map.Entry<String, Object> courseEntry :
                                                                        courseItem.entrySet()) {
                                                                    if (courseEntry.getValue() != null) {
                                                                        switch (courseEntry.getKey()) {
                                                                            case "courBeginTime":
                                                                                //课程开始时间
                                                                                courseVideoUrl.setCourBeginTime(sdf.parse(String.valueOf(courseEntry.getValue())).getTime());
                                                                                break;
                                                                            case "courEndTime":
                                                                                //课程结束时间
                                                                                courseVideoUrl.setCourEndTime(sdf.parse(String.valueOf(courseEntry.getValue())).getTime());
                                                                                break;
                                                                            case "courId":
                                                                                //课程Id
                                                                                courseVideoUrl.setCourId(Integer.valueOf(String.valueOf(courseEntry.getValue())));
                                                                                break;
                                                                            case "deviceViewList":
                                                                                //教室绑定的设备视角
                                                                                List<HashMap<String, Object>> list = CommonUtils.jsonToHashMapList(CommonUtils.objectToJson(courseEntry.getValue()));
                                                                                if (list != null && !list.isEmpty()) {
                                                                                    courseVideoUrl.setDeviceViewList(list.stream()
                                                                                            .map(item -> {
                                                                                                KeduDeviceVideoUrlVO deviceVideoUrl = new KeduDeviceVideoUrlVO();
                                                                                                if (item != null) {
                                                                                                    for (Map.Entry<String, Object> entry :
                                                                                                            item.entrySet()) {
                                                                                                        if (entry.getValue() != null) {
                                                                                                            switch (entry.getKey()) {
                                                                                                                case "deviViewNum":
                                                                                                                    //视角编号：1: '教师1',2: '教师2',3: '学生1',4: '学生2',5: 'PPT',6: '电子白板',7: '合成通道'
                                                                                                                    deviceVideoUrl.setDeviViewNum(Integer.valueOf(String.valueOf(entry.getValue())));
                                                                                                                    break;
                                                                                                                case "deviceStatus":
                                                                                                                    //设备状态
                                                                                                                    deviceVideoUrl.setDeviceStatus(Integer.valueOf(String.valueOf(entry.getValue())));
                                                                                                                    break;
                                                                                                                case "playUrl":
                                                                                                                    //主流通道直播播放url
                                                                                                                    deviceVideoUrl.setPlayUrl(String.valueOf(entry.getValue()));
                                                                                                                    break;
                                                                                                                case "gbId":
                                                                                                                    //主流通道设备视角国标ID
                                                                                                                    deviceVideoUrl.setGbId(String.valueOf(entry.getValue()));
                                                                                                                    break;
                                                                                                                case "secondPlayUrl":
                                                                                                                    //辅流通道直播播放url
                                                                                                                    deviceVideoUrl.setSecondPlayUrl(String.valueOf(entry.getValue()));
                                                                                                                    break;
                                                                                                                case "secondGbId":
                                                                                                                    //辅流通道设备视角国标ID
                                                                                                                    deviceVideoUrl.setSecondGbId(String.valueOf(entry.getValue()));
                                                                                                                    break;
                                                                                                            }
                                                                                                        }
                                                                                                    }
                                                                                                }
                                                                                                return deviceVideoUrl;
                                                                                            })
                                                                                            .collect(Collectors.toList()));
                                                                                }
                                                                                break;
                                                                            case "subjCode":
                                                                                //科目编号
                                                                                courseVideoUrl.setSubjCode(String.valueOf(courseEntry.getValue()));
                                                                                break;
                                                                            case "subjName":
                                                                                //科目名称
                                                                                courseVideoUrl.setSubjName(String.valueOf(courseEntry.getValue()));
                                                                                break;
                                                                            case "teacCodes":
                                                                                //老师编号
                                                                                courseVideoUrl.setTeacCodes(CommonUtils.objToList(courseEntry.getValue(), String.class));
                                                                                break;
                                                                            case "teacNames":
                                                                                //老师名称
                                                                                courseVideoUrl.setTeacNames(CommonUtils.objToList(courseEntry.getValue(), String.class));
                                                                                break;
                                                                            case "yearTerm":
                                                                                //学年学期
                                                                                courseVideoUrl.setYearTerm(String.valueOf(courseEntry.getValue()));
                                                                                break;
                                                                            case "needAttNum":
                                                                                //应到学生数
                                                                                courseVideoUrl.setNeedAttNum(Integer.valueOf(String.valueOf(courseEntry.getValue())));
                                                                                break;
                                                                            case "actualAttNum":
                                                                                //实到学生数
                                                                                courseVideoUrl.setActualAttNum(Integer.valueOf(String.valueOf(courseEntry.getValue())));
                                                                                break;
                                                                            case "lateNum":
                                                                                //迟到学生数
                                                                                courseVideoUrl.setLateNum(Integer.valueOf(String.valueOf(courseEntry.getValue())));
                                                                                break;
                                                                            case "attPercent":
                                                                                //到勤率
                                                                                courseVideoUrl.setAttPercent(Double.valueOf(String.valueOf(courseEntry.getValue())));
                                                                                break;
                                                                            case "frontRowPercent":
                                                                                //前排就座率
                                                                                courseVideoUrl.setFrontRowPercent(Double.valueOf(String.valueOf(courseEntry.getValue())));
                                                                                break;
                                                                            case "risePercent":
                                                                                //抬头率
                                                                                courseVideoUrl.setRisePercent(Double.valueOf(String.valueOf(courseEntry.getValue())));
                                                                                break;
                                                                            case "frontFullPercent":
                                                                                //前排满座率
                                                                                courseVideoUrl.setFrontFullPercent(Double.valueOf(String.valueOf(courseEntry.getValue())));
                                                                                break;
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        } catch (Exception e) {
                                                            log.error("error {}", e.getMessage());
                                                        }
                                                        return courseVideoUrl;
                                                    })
                                                    .collect(Collectors.toList()));
                                        }
                                        break;
                                }
                            }
                        }
                        return videoUrlWithExtInfo;
                    }).collect(Collectors.toList());
        }
        return videoUrlList;
    }

    @Override
    public Pagination<KeduRoomDetailVO> pageKeduRoomDetail(Integer pageSize, Integer pageNum, String classroomCode, Long startDateTime, Long endDateTime) throws Exception {
        if (pageSize == null) {
            throw new TyrfingServiceException(TyrfingErrorCode.LACK_OF_PARAMETER, "缺少每页数量.");
        }
        if (pageNum == null) {
            throw new TyrfingServiceException(TyrfingErrorCode.LACK_OF_PARAMETER, "缺少当前页号.");
        }
        if (startDateTime == null) {
            throw new TyrfingServiceException(TyrfingErrorCode.LACK_OF_PARAMETER, "缺少开始日期.");
        }
        if (endDateTime == null) {
            throw new TyrfingServiceException(TyrfingErrorCode.LACK_OF_PARAMETER, "缺少结束日期.");
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("imagShotTime").gte(new Date(startDateTime)).lte(new Date(endDateTime)));

        if (StringUtils.isNotBlank(classroomCode)) {
            query.addCriteria(Criteria.where("clroCode").is(classroomCode));
        }
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        query.with(pageable);

        List<KeduRoomDetailVO> roomDetails = mongoTemplate.find(query, KeduRoomDetailVO.class);

        long totalCount = mongoTemplate.count(query.skip(-1).limit(-1), KeduRoomDetailVO.class);

        List<KeduRoomDetailVO> keduRoomDetailVOList = roomDetails.stream()
                .map(roomDetail -> {
                    KeduRoomDetailVO roomDetailVO = new KeduRoomDetailVO();
                    roomDetailVO.setClroSeatCount(roomDetail.getClroSeatCount());
                    roomDetailVO.setClroFrontSeatCount(roomDetail.getClroFrontSeatCount());
                    roomDetailVO.setAttendanceCount(roomDetail.getAttendanceCount());
                    roomDetailVO.setAttendanceFaceCount(roomDetail.getAttendanceFaceCount());
                    roomDetailVO.setFrontAttendancetCount(roomDetail.getFrontAttendancetCount());
                    roomDetailVO.setImagShotTime(roomDetail.getImagShotTime());
                    roomDetailVO.setClroCode(roomDetail.getClroCode());
                    return roomDetailVO;
                })
                .collect(Collectors.toList());

        Pagination<KeduRoomDetailVO> pagination = new Pagination<>(pageSize, pageNum);
        pagination.setData(keduRoomDetailVOList);
        pagination.setTotal((int) totalCount);

        return pagination;
    }
}
